package com.colin.juc.lock.spinlock;

import java.util.concurrent.atomic.AtomicReference;

/**
 * Created by Colin on 2020/4/18 20:49
 * email: colinzhaodong@gmail.com
 * desc: //todo
 *
 * @author zhaod
 */
public class SpinLock {
	private final AtomicReference<Thread> sign = new AtomicReference<>();

	public void lock(){
		Thread current = Thread.currentThread();
		while (!sign.compareAndSet(null,current)){
//			System.out.println("自旋获取失败，再次尝试");
		}
	}
	public void unlock(){
		Thread current = Thread.currentThread();
		sign.compareAndSet(current,null);
	}

	public static void main(String[] args) {
		SpinLock spinLock = new SpinLock();
		Runnable runnable = () -> {
			System.out.println(Thread.currentThread().getName() + "开始尝试获取自旋锁");
			spinLock.lock();
			System.out.println(Thread.currentThread().getName() + "获取到了自旋锁");
			try {
				Thread.sleep(300);
			} catch (InterruptedException e) {
				e.printStackTrace();
			} finally {
				spinLock.unlock();
				System.out.println(Thread.currentThread().getName() + "释放了自旋锁");
			}
		};
		Thread thread1 = new Thread(runnable);
		thread1.setName("thread1");
		Thread thread2 = new Thread(runnable);
		thread2.setName("thread2");
		thread1.start();
		thread2.start();
	}
}
